//
//  CoreCitySearchDB.swift
//  Swift-app开发基础架构
//
//  Created by 朱凯 on 2017/10/19.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

import UIKit

import FMDB

struct KZProvince {
    var id: String = ""
    var name: String = ""
}
struct KZCity {
    var id: String = ""
    var name: String = ""
}
struct KZArea {
    var id: String = ""
    var name: String = ""
}

class KZCityDataBase: KZDataBase {

    static func queryAllProvinces() -> [KZProvince] {
        
        openDB()
        
        // 创建数组变量，用于存储返回值
        var list = [KZProvince]()
        
        // 开始查询
        _dbQueue.inDatabase { (db) in
            
            db.beginTransaction()
            
            let set: FMResultSet? = try? db.executeQuery("SELECT * FROM common_province", values: [])
            if let set = set {
                while set.next() {
                    let province = KZProvince(id: set.string(forColumn: "provinceID")!,
                                                name: set.string(forColumn: "province")!)
                    list.append(province)
                }
                set.close();
            }
            db.commit()
        }
        return list
    }
    
    static func queryAllCitys(withProvinceID id: String) -> [KZCity] {
        
        openDB()
        
        // 创建数组变量，用于存储返回值
        var list = [KZCity]()
        
        // 开始查询
        _dbQueue.inDatabase { (db) in
            
            db.beginTransaction()
            
            let set: FMResultSet? = try? db.executeQuery("SELECT * FROM common_city where father = ?", values: ["\(id)"])
            if let set = set {
                while set.next() {
                    let city = KZCity(id: set.string(forColumn: "cityID")!,
                                        name: set.string(forColumn: "city")!)
                    list.append(city)
                }
                set.close();
            }
            db.commit()
        }
        return list
    }
    
    static func queryAllAreas(withCityID id: String) -> [KZArea] {
        
        openDB()
        
        // 创建数组变量，用于存储返回值
        var list = [KZArea]()
        
        // 开始查询
        _dbQueue.inDatabase { (db) in
            
            db.beginTransaction()
            
            let set: FMResultSet? = try? db.executeQuery("SELECT * FROM common_area where father = ?", values: ["\(id)"])
            if let set = set {
                while set.next() {
                    let area = KZArea(id: set.string(forColumn: "areaID")!,
                                        name: set.string(forColumn: "area")!)
                    list.append(area)
                }
                set.close();
            }
            db.commit()
        }
        return list
    }
}
